package pl.skubicha.utils;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.authentication.encoding.PasswordEncoder;

import pl.skubicha.domain.Subjects;
import pl.skubicha.domain.Users;
import pl.skubicha.response.StudentsForGroupsDTO;
import pl.skubicha.response.SubjectForGroupsDTO;
import pl.skubicha.response.UserDTO;

public class UserMapper {

	public static UserDTO map( final Users user ) {
		final UserDTO dto = new UserDTO();
		dto.setId( user.getId() );
		dto.setFirstName( user.getFirstName() );
		dto.setLastName( user.getLastName() );
		dto.setUserName( user.getLogin() );
		dto.setStatus( user.isStatus() );
		dto.setEmail( user.getEmail() );
		dto.setPassword( StringUtils.EMPTY );
		dto.setRoles( user.getRoles() );
		dto.setAlbumNumber( user.getAlbumNumber() );
		dto.setGroups( user.getGroups() );
		dto.setSubjects( user.getSubjects() );
		dto.setGrades( user.getPartialGrades() );

		return dto;
	}

	public static Users map( final UserDTO dto ) {
		final Users user = new Users();
		user.setFirstName( dto.getFirstName() );
		user.setLastName( dto.getLastName() );
		user.setLogin( dto.getUserName() );
		user.setEmail( dto.getEmail() );
		user.setStatus( dto.isStatus() );
		user.setRoles( dto.getRoles() );
		user.setAlbumNumber( dto.getAlbumNumber() );
		user.setGroups( dto.getGroups() );
		user.setPartialGrades( dto.getGrades() );
		user.setSubjects( dto.getSubjects() );

		final PasswordEncoder encoder = new Md5PasswordEncoder();
		user.setPassword( encoder.encodePassword( dto.getPassword(), null ) );

		return user;
	}

	public static List< UserDTO > map( final Iterable< Users > users ) {
		final List< UserDTO > dtos = new ArrayList< UserDTO >();

		for ( final Users user : users ) {
			dtos.add( map( user ) );
		}

		return dtos;
	}

	public static StudentsForGroupsDTO mapStudentsToGroupsDTO( final Users user ) {
		final StudentsForGroupsDTO dto = new StudentsForGroupsDTO();
		dto.setId( user.getId() );
		dto.setStudentFirstName( user.getFirstName() );
		dto.setStudentLastName( user.getLastName() );

		return dto;
	}

	public static Users map( final StudentsForGroupsDTO dto ) {
		final Users user = new Users();
		user.setId( dto.getId() );
		user.setFirstName( dto.getStudentFirstName() );
		user.setLastName( dto.getStudentLastName() );

		return user;
	}

	public static List< StudentsForGroupsDTO > mapStudentsToGroupsDTO( final Iterable< Users > users ) {
		final List< StudentsForGroupsDTO > dtos = new ArrayList< StudentsForGroupsDTO >();

		for ( final Users user : users ) {
			dtos.add( mapStudentsToGroupsDTO( user ) );
		}

		return dtos;
	}
}
